<?php
namespace Erp\C\Orders\Tn\Shipping;
use Erp\C\Orders\Tn\Shipping\Shipping;
use Erp\C\Orders\Tn\Api\ApiYtModule;
use Fn;
/**
 * 云途API
 */
class Yt extends Shipping{
	private $filename,$Header,$root_dir,$api_yt;
	private $ordersRes=array();
	//初始化API请求对象
	public function __construct(){
		$this->api_yt = new ApiYtModule();
	}

	/**
	 *获取TN入口方法
	 *@param array $Orders array(1,2,3) || string 2
	 */
	public function getTn($Orders){
		// Fn\App::log('kim_Yt',$Orders,"万邑通获取TN内部");

		if(!is_array($Orders)){
			$Orders = array($Orders);
		}
		$count = count($Orders);
		$multi_num = 5;
		$for_num = ceil($count/$multi_num);
		for($i = 0;$i<$for_num;$i++){
			$s = $i*$multi_num;

			$tmp_arr = array_slice($Orders,$s,$multi_num);

			$this->ytApiMgr($tmp_arr);
		}
		// var_dump($tmp_arr);
	}

	/**
	 *获取lable入口
	 *@param array $Orders 一维数组
	 */
	public function getLable($Orders){
		$this->_getPdf($Orders);
	}

	/**
	 *获取tn成功后调用此方法获取面单Pdf
	 *@param array $Orders 一维数组订单号
	 */
	private function _getPdf($Orders){
		if(!$Orders){
			echo "无订单".__LINE__;
		}
		$this->_requestLable($Orders);//获取Lable标签
	}

	/**
	 *获取地万邑通TN流程
	 *@param array $tmp_arr 数组 订单号
	 */
	public function ytApiMgr($tmp_arr){

		$request_data = $this->createPackageParams($tmp_arr);			//生成请求数据

		Fn\App::log('kim_dsf',$request_data,"DSF获取TN数据");

		$response = $this->api_yt->createAndConfirmPackages($request_data);	//api提交数据
		Fn\App::log('kim_dsf',$response,"DSF获取TN数据");
		$this->disposePackageReturn($response);				//处理响应结果



	}

    //报关金额
    private function _getCustomsTotalValue($productsTotalVal) {
        $v = round($productsTotalVal * 1, 2);
        $v = ($v < 36 ? ($v / 2) : (18 - ($v - floor($v))));
        $v = round($v, 2);
        $tmp = str_replace('.', '', $v . '');
        $tmp = chunk_split($tmp . '', 1, '-');
        $tmp = max(explode('-', $tmp)) * 1;
        $tmp = ($tmp > 0 && $tmp < 10) ? $tmp : 9;
        $doct = $v - floor($v);
        $v = ($v > 10) ? ("$tmp.$doct") : $v;

        return round($v, 2);
    }

	/*
		获取订单产品的相关信息
	*/
	private function _getOrderProductInfo($productList){
		$total_price = 0;
		$quantity = 0;
		$info = array();
		foreach ($productList as  $v) {
			$total_price += $v['orders_item_total_price_usd'];
			$quantity += $v['orders_product_quantity'];
		}
		$info = array('totalPrice'=>$total_price,'quantity'=>$quantity);
		return $info;
	}

	/**
	 *创建线上包裹数据格式
	 *@param array $tmp_arr
	 *@return array
	 */
	public  function createPackageParams($tmp_arr){
		$order = A("Orders");
		$multi_request = array();
		// $ebayOrdersItem=M("ebay_orders_item");
		// $ebayOrders = M('ebay_orders');
		foreach ($tmp_arr as $key=>$ordersId){		//组装批量请求数据
			$orderInfo = $order->combinOrderInfo($ordersId);	//获取订单信息
			//$orderInfo = $this->htmlspecialData($orderInfo);	//过滤数据
			$country = $orderInfo['orders_delivery_country_iso'];		//全名||2位CODE
			$shipping = $orderInfo['orders_shipping_method'];
			$shippingArr = $this->_shippingEnumerate($shipping);		// 运输方式转换 :ERP代码 ---->API标准代码
			$shipping = $shippingArr['shipCode'];
			$header = $shippingArr['header'];
			// $warehouseCode = $shippingArr['warehouseCode'];
			// $dispatchType = $shippingArr['dispatchType'];
			$shopName = $orderInfo['orders_shop_name'];

			// $ebayOrdersRes = $ebayOrders->where('ebay_orders_id = "'.$orderInfo['orders_original_id'].'"') -> find();
			// $ebayOrdersId = trim($ebayOrdersRes['ebay_orders_id']);
			// $isAuctionOrders = strtolower(trim($orderInfo['orders_tn']))==='auction'? true: false;	//是否竞拍订单

			//收货人信息
			$city = $orderInfo['orders_delivery_city'];		//收货人城市
			$name = $orderInfo['orders_delivery_name'];		//收货人姓名
			$phone = $orderInfo['orders_delivery_tel'];		//收货人电话
			$phone = empty($phone)?'00':$phone;
			$postCode = $orderInfo['orders_delivery_postcode'];//收货人邮编
			$state = $orderInfo['orders_delivery_state'];		//收货人州、省
			$address1 = $orderInfo['orders_delivery_address']." ";	//收货人详细地址
			$address2 = $orderInfo['orders_delivery_address2'];//收货人详细地址2
			$address = $address1.' '.$address2;
			//一个订单内的所有产品信息
			$productList = $orderInfo['orders_items'];
			$weight = $orderInfo['orders_weight'];

			$count = 0;
			$price = 0;
			foreach ($productList as $orderProduct){
				$count += $orderProduct['orders_product_quantity'];
				$price += $orderProduct['orders_item_total_price_usd'];
			}

			$price = $this->_getCustomsTotalValue($price);//申报价格在1-20美金
			$unitPrice = $price/$count;
			$unitPrice = round($unitPrice,4);
			$unitWeight = $weight/$count;
			$unitWeight = round($unitWeight,4);
			$tmp=array();
			foreach ($productList as $key=>$orderProduct){
				$productId=$orderProduct['product_id'];
				$product=A('Product')->getProduct($productId);
				$CustomsInfo=$this->getRealCustomsName($productId);	//报关名
				$categoryCnDesc = $CustomsInfo['ClassnameForCustomsCn'];//报关中文名
				$categoryEnDesc = $CustomsInfo['ClassnameForCustoms'];//报关英文名
				$tmp[$key]=array(
					"ApplicationName"=>trim($categoryEnDesc),
					"Qty"=>$count,
					"UnitPrice"=>$unitPrice,
					"UnitWeight"=>$unitWeight,
					'PickingName'=>$categoryCnDesc
				);
				break;
			}

			if($country=='UK'){
				$country = 'GB';
			}
			//ERP中老挝CODE和万邑通不匹配，进行转换
			if($country=="LO"){
				$country = "LA";
			}

			//请求信息模板
			$content = array(
				'OrderNumber'=>$ordersId,
				'ShippingMethodCode'=>$shipping,
				'PackageNumber'=>1,//$count,
				'Weight'=>round($weight,3),
				'ShippingInfo'=>array(
					'CountryCode'=>$country,
					'ShippingFirstName'=>$name,
					'ShippingAddress'=>$address1,
					'ShippingAddress1'=>$address2,
					'ShippingCity'=>$city,
					'ShippingState'=>$state,
					'ShippingZip'=>$postCode,
					'ShippingPhone'=>$phone,
				),
				// 'SenderInfo'=>array(

				// ),
				// 'IsReturn'=>1,
				'ApplicationInfos'=>$tmp,
			);
			$res = json_encode(array($content));
			$multi_request[$ordersId] = array('post'=>$res,'header'=>$header,'url'=>$this->api_yt->url);
			unset($res);unset($content);
		}
		return $multi_request;
	}

	/**
	 *处理提交包裹所返回的响应
	 *@param array $multi_request_res
	 *	1:"待取TN",
	 *	6:"TN失败",
	 *	7:"已取TN",
	 *	8:"PDF失败"
	 *	99: 成功
	 */
	public  function disposePackageReturn($multi_request_res){
		$o_model = A("Orders");
		$success_id = array();	//记录成功的订单
		if($multi_request_res){ //此处判断是否请求了接口数据，如果手动获取tn时订单已有tn就不会请求接口，此时这个返回数据就是false
			foreach ($multi_request_res as $k=>$v){		//array("orders_id"=>$info)
				if(!is_array($v)){
					$v = json_decode($v,true);
				}
				if($v['ResultCode'] == '0000' && isset($v['ResultCode'])){
					$tn = $v['Item'][0]['OrderId'];
					$ordersData = array();
					$ordersData['orders_tn'] = $tn;
					if(!$ordersData['orders_tn'])continue;
					// $ordersStatus = $o_model->where("orders_id=$k")->getField("orders_status");
					$ordersStatus = $o_model->getOrdersStatus();
					if($ordersStatus == '300'){
						$ordersData['orders_status_children'] = 7;
					}
					// $o_model->where("orders_id=$k")->save($ordersData);
					$o_model->saveData($ordersData);
					$this->saveOrderHistory($k,"获取云途TN成功--".$ordersData['orders_tn']);
				}elseif (isset($v['Item'][0]) && $v['Item'][0]) {
					$tn = $v['Item'][0]['OrderId'];
					if($tn && strlen($tn)>5){
						$ordersData = array();
						$ordersData['orders_tn'] = $tn;
						if(!$ordersData['orders_tn'])continue;
						// $ordersStatus = $o_model->where("orders_id=$k")->getField("orders_status");
						$ordersStatus = $o_model->getOrdersStatus();
						if($ordersStatus == '300'){
							$ordersData['orders_status_children'] = 7;
						}
						// $o_model->where("orders_id=$k")->save($ordersData);
						$o_model->saveData($ordersData);
						$this->saveOrderHistory($k,"获取云途TN成功--".$ordersData['orders_tn']);
						continue;
					}
					$errorsMsgs = $v['Item'][0]['Feedback'];
					// $return = strpos($errorsMsgs,'参考单号已存在');
					// if($return !== false){
					// 	$this->_findTn($k);
					// 	continue;
					// }
					$ordersData = array();
					$ordersData['orders_status_children'] = 6;
					$o_model->saveData($ordersData);
					$this->saveOrderHistory($k,"获取云途TN失败:".$errorsMsgs);
					// $o_model->where("orders_id=$k and orders_status = 300")->setField("orders_status_children",6); 		//取TN失败
				}
			}
		}
	}

	//单独获取Lable标签
	private function _requestLable($orders){
		$oModel=A("Orders");
		// $res=$oModel->where("orders_id in(".implode(",", $orders).")")->select();
		$res = $oModel->getOrders($orders);
		$root_dir = "./Public/Data/Files/";
		foreach ($res as $v) {
			$time = time();
			$orders_tn = $v['orders_tn'];
			$ordersId = $v['orders_id'];
			$time = $v['orders_import_time'];
			$dir_local_root = $root_dir.date('Ymd',$time)."/";
			$filename = $ordersId.'.pdf';
			//删除PDF
			if(file_exists($dir_local_root.$filename)){
				@unlink($dir_local_root.$filename);
			}
			$shippingArr = $this->_shippingEnumerate($v['orders_shipping_method']);
			$shipping = $shippingArr['shipCode'];
			$warehouseCode = $shippingArr['warehouseCode'];
			$header = $shippingArr['header'];
			$arr = array($ordersId);
			$arr = json_encode($arr);
			$response = $this->api_yt->createPackageLable($arr,$header);
			$response = json_decode($response,true);
			$contentUrl = $response['Item'][0]['Url'];
			$content = file_get_contents($contentUrl);
			// $content = $this->_getPdfFileStream($response,$ordersId,$oModel);//获得pdf文件流
			//把获得的面单pdf保存到指定目录
			$is_exists = $this->saveShippingLable($dir_local_root,$filename,$content);
			Fn\App::log('yt_Dff_error',array(
				'response'=>$response,
				'isExists'=>$is_exists,
				'url'=>$dir_local_root.$filename
			),"云途请求PDF调试");
			if(!$is_exists){
				sleep(2);
				$response = $this->api_yt->createPackageLable($arr,$header);
				$response = json_decode($response,true);
				$contentUrl = $response['Item'][0]['Url'];
				$content = file_get_contents($contentUrl);
				$is_exists = $this->saveShippingLable($dir_local_root,$filename,$content);
			}
			if($is_exists){
				$saveData = array();
				$saveData['orders_pdf_exist'] = 1;
				$ordersStatus = $v["orders_status"];
				if($ordersStatus == '300'){
					$saveData['orders_status_children'] = 99;
				}
				$oModel->saveData($saveData);
				// $oModel->where("orders_id=$ordersId")->save($saveData);
				// chmod($filename,0777);
				$this->saveOrderHistory($ordersId,'获取云途PDF成功');

			}else{
				// $oModel->where("orders_id=$ordersId  and orders_status = 300")->save(array(
				// 		'orders_status_children'=>8
				// ));
				$saveData = array();
				$ordersStatus = $v["orders_status"];
				if($ordersStatus == '300'){
					$saveData['orders_status_children'] = 8;
				}
				$oModel->saveData($saveData);
				$this->saveOrderHistory($ordersId,'获取云途PDF失败');
			}
		}
	}

	//ERP运输方式转换成API标准的运输方式
	private function _shippingEnumerate($name){
		switch($name){
			case 'YTPY':
				return array('shipCode'=>'TWYZA','warehouseCode'=>'DG','header'=>$this->api_yt->Header);
			case 'YTPYYW':
				return array('shipCode'=>'TWYZA','warehouseCode'=>'YW','header'=>$this->api_yt->Header2);
			default:
				return false;
		}
	}
}